<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>产品质量标准配置 - {{ productInfo.name }}</span>
          <div class="right-menu">
            <el-button icon="Back" @click="goBack">返回</el-button>
            <el-button 
              type="primary" 
              @click="saveStandardConfig" 
              v-hasPermi="['qep:product:edit']"
            >保存配置</el-button>
          </div>
        </div>
      </template>

      <el-descriptions title="产品信息" :column="3" border size="small">
        <el-descriptions-item label="产品编码">{{ productInfo.code }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ productInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="产品分类">{{ productInfo.categoryName }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">质量标准关联</el-divider>
      
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAddStandard"
            v-hasPermi="['qep:product:edit']"
          >添加标准</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDeleteStandard"
            v-hasPermi="['qep:product:edit']"
          >删除</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="standardList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标准编号" align="center" prop="code" />
        <el-table-column label="标准名称" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="标准类型" align="center" prop="typeName" />
        <el-table-column label="版本" align="center" prop="version" />
        <el-table-column label="适用条件" align="center" prop="condition" :show-overflow-tooltip="true" />
        <el-table-column label="是否主标准" align="center">
          <template #default="scope">
            <el-tag 
              :type="scope.row.isPrimary === 1 ? 'success' : 'info'"
              @click="handleSetPrimary(scope.row)"
              style="cursor: pointer;"
            >
              {{ scope.row.isPrimary === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              icon="Edit" 
              @click="handleEditStandard(scope.row)" 
              v-hasPermi="['qep:product:edit']"
            >编辑</el-button>
            <el-button 
              link 
              type="danger" 
              icon="Delete" 
              @click="handleDeleteSingle(scope.row)" 
              v-hasPermi="['qep:product:edit']"
            >删除</el-button>
            <el-button 
              link 
              type="primary" 
              icon="View" 
              @click="handleViewStandard(scope.row)" 
              v-hasPermi="['qep:product:query']"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getStandardList"
      />
    </el-card>

    <!-- 添加/修改关联标准对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="standardRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="选择标准" prop="standardId">
          <el-select
            v-model="form.standardId"
            placeholder="请选择标准"
            filterable
            remote
            :remote-method="remoteSearchStandard"
            :loading="loading"
            style="width: 100%"
            @change="handleStandardChange"
          >
            <el-option
              v-for="item in standardOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div class="standard-option">
                <div>{{item.name}} ({{item.code}})</div>
                <div class="standard-option-desc">{{item.typeName}} | 版本: {{item.version}}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本" prop="version" v-if="form.standardId">
          <el-input v-model="form.version" placeholder="请输入版本" disabled />
        </el-form-item>
        <el-form-item label="适用条件" prop="condition">
          <el-input v-model="form.condition" type="textarea" placeholder="请输入适用条件" />
        </el-form-item>
        <el-form-item label="设为主标准" prop="isPrimary">
          <el-radio-group v-model="form.isPrimary">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关键参数" prop="parameters">
          <el-table :data="form.parameters" style="width: 100%">
            <el-table-column label="参数名称" prop="name" min-width="120">
              <template #default="scope">
                <el-input v-model="scope.row.name" placeholder="参数名称" />
              </template>
            </el-table-column>
            <el-table-column label="参数值" prop="value" min-width="120">
              <template #default="scope">
                <el-input v-model="scope.row.value" placeholder="参数值" />
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="unit" min-width="80">
              <template #default="scope">
                <el-input v-model="scope.row.unit" placeholder="单位" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  link
                  icon="Delete" 
                  @click="removeParameter(scope.$index)" 
                />
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" icon="Plus" @click="addParameter">添加参数</el-button>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看标准详情对话框 -->
    <el-dialog title="标准详情" v-model="viewDialogVisible" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="标准编号">{{ standardDetail.code }}</el-descriptions-item>
        <el-descriptions-item label="标准名称">{{ standardDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="标准类型">{{ standardDetail.typeName }}</el-descriptions-item>
        <el-descriptions-item label="标准版本">{{ standardDetail.version }}</el-descriptions-item>
        <el-descriptions-item label="发布日期">{{ standardDetail.publishDate }}</el-descriptions-item>
        <el-descriptions-item label="实施日期">{{ standardDetail.implementDate }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="center">标准内容</el-divider>
      
      <div v-html="standardDetail.content"></div>
      
      <el-divider content-position="center">标准参数</el-divider>
      
      <el-table :data="standardDetail.parameters || []" border>
        <el-table-column label="参数名称" prop="name" min-width="120" />
        <el-table-column label="参数类型" prop="type" min-width="100" />
        <el-table-column label="标准值" prop="nominalValue" min-width="100" />
        <el-table-column label="最小值" prop="minValue" min-width="100" />
        <el-table-column label="最大值" prop="maxValue" min-width="100" />
        <el-table-column label="单位" prop="unit" min-width="80" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getProduct } from "@/api/qep/product";
import { searchStandard, getStandard } from "@/api/qep/standard";
import { listProductStandard, getProductStandard, addProductStandard, updateProductStandard, delProductStandard, delProductStandards, setPrimaryStandard } from "@/api/qep/productStandard";
import { listStandardParam } from "@/api/qep/standardParam";
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();

// 产品信息
const productInfo = ref({});
// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非多个禁用
const multiple = ref(true);
// 总条数
const total = ref(0);
// 标准表格数据
const standardList = ref([]);
// 标准选项数据
const standardOptions = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 查看标准详情弹窗
const viewDialogVisible = ref(false);
// 标准详情
const standardDetail = ref({});

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  productId: undefined
});

// 表单参数
const form = ref({
  id: undefined,
  productId: undefined,
  standardId: undefined,
  version: undefined,
  condition: undefined,
  isPrimary: 0,
  parameters: [],
  remark: undefined
});

// 表单校验
const rules = ref({
  standardId: [
    { required: true, message: "请选择标准", trigger: "change" }
  ],
  condition: [
    { required: true, message: "请输入适用条件", trigger: "blur" }
  ]
});

// 表单引用
const standardRef = ref();

/* 查询产品详情 */
function getProductInfo(id) {
  getProduct(id).then(response => {
    productInfo.value = response.data || {};
    queryParams.value.productId = id;
    getStandardList();
  });
}

/* 查询关联标准列表 */
function getStandardList() {
  loading.value = true;
  listProductStandard(queryParams.value.productId).then(response => {
    standardList.value = response.data || [];
    total.value = standardList.value.length;
    loading.value = false;
  });
}

/* 远程搜索标准 */
function remoteSearchStandard(query) {
  if (query) {
    loading.value = true;
    searchStandard({ searchValue: query }).then(response => {
      standardOptions.value = response.data || [];
      loading.value = false;
    });
  } else {
    standardOptions.value = [];
  }
}

/* 标准选择改变事件 */
function handleStandardChange(value) {
  if (value) {
    const selected = standardOptions.value.find(item => item.id === value);
    if (selected) {
      form.value.version = selected.version;
      // 获取标准参数
      listStandardParam({ standardId: value }).then(response => {
        const params = response.data || [];
        // 转换参数格式
        form.value.parameters = params.map(p => ({
          name: p.name,
          value: p.nominalValue || '',
          unit: p.unit || ''
        }));
      });
    }
  } else {
    form.value.version = undefined;
    form.value.parameters = [];
  }
}

/* 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/* 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    productId: route.query.id,
    standardId: undefined,
    version: undefined,
    condition: undefined,
    isPrimary: 0,
    parameters: [],
    remark: undefined
  };
  standardRef.value?.resetFields();
}

/* 添加标准按钮操作 */
function handleAddStandard() {
  reset();
  open.value = true;
  title.value = "添加关联标准";
}

/* 编辑标准按钮操作 */
function handleEditStandard(row) {
  reset();
  const id = row.id;
  // 获取标准关联详细信息
  getProductStandard(id).then(response => {
    const data = response.data || {};
    form.value = {
      id: data.id,
      productId: data.productId,
      standardId: data.standardId,
      version: row.version,
      condition: data.condition,
      isPrimary: data.isPrimary,
      parameters: data.parameters || [],
      remark: data.remark
    };
    
    // 设置当前标准选项，以便显示
    standardOptions.value = [
      {
        id: row.standardId,
        code: row.code,
        name: row.name,
        typeName: row.typeName,
        version: row.version
      }
    ];
    
    open.value = true;
    title.value = "修改关联标准";
  });
}

/* 查看标准按钮操作 */
function handleViewStandard(row) {
  // 获取标准详情
  getStandard(row.standardId).then(response => {
    standardDetail.value = response.data || {};
    
    // 获取标准参数
    listStandardParam({ standardId: row.standardId }).then(response => {
      standardDetail.value.parameters = response.data || [];
      viewDialogVisible.value = true;
    });
  });
}

/* 提交按钮 */
function submitForm() {
  standardRef.value.validate(valid => {
    if (valid) {
      const formData = {
        id: form.value.id,
        productId: form.value.productId,
        standardId: form.value.standardId,
        condition: form.value.condition,
        isPrimary: form.value.isPrimary,
        parameters: form.value.parameters,
        remark: form.value.remark
      };
      
      if (form.value.id != undefined) {
        updateProductStandard(formData).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getStandardList();
        });
      } else {
        addProductStandard(formData).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getStandardList();
        });
      }
    }
  });
}

/* 删除按钮操作 */
function handleDeleteStandard() {
  const standardIds = ids.value;
  ElMessageBox.confirm('是否确认删除选中的关联标准?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    delProductStandards(standardIds).then(() => {
      ElMessage.success("删除成功");
      getStandardList();
    });
  }).catch(() => {});
}

/* 删除单个标准 */
function handleDeleteSingle(row) {
  ElMessageBox.confirm('是否确认删除该关联标准?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    delProductStandard(row.id).then(() => {
      ElMessage.success("删除成功");
      getStandardList();
    });
  }).catch(() => {});
}

/* 设置为主标准 */
function handleSetPrimary(row) {
  if (row.isPrimary === 1) {
    return;
  }
  
  ElMessageBox.confirm('是否将该标准设置为主标准?', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    setPrimaryStandard(row.id, row.productId).then(() => {
      ElMessage.success("设置成功");
      getStandardList();
    });
  }).catch(() => {});
}

/* 返回按钮操作 */
function goBack() {
  router.go(-1);
}

/* 添加参数行 */
function addParameter() {
  form.value.parameters.push({
    name: '',
    value: '',
    unit: ''
  });
}

/* 删除参数行 */
function removeParameter(index) {
  form.value.parameters.splice(index, 1);
}

/* 保存标准配置 */
function saveStandardConfig() {
  ElMessage.success("标准配置保存成功");
}

/* 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  multiple.value = !selection.length;
}

onMounted(() => {
  if (route.query.id) {
    getProductInfo(route.query.id);
  }
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-menu {
  margin-left: auto;
}

.standard-option {
  display: flex;
  flex-direction: column;
}

.standard-option-desc {
  font-size: 12px;
  color: #909399;
}

.el-divider {
  margin: 20px 0;
}

.mb8 {
  margin-bottom: 8px;
}
</style> 